package com.mission.schedule.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.activity.NewFriendsActivity;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.NoteTypeBean;
import com.mission.schedule.bean.qd606.NoteShareBean;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 下载和同步好友
 * Created by liwei on 2017/3/2.
 */

public class NewFriendService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
        App.getHttpQueues().cancelAll("downf");
    }


    SharedPrefUtil sharedPrefUtil;
    String UserId = "";
    String downtime = "2016-01-01";

    @Override
    public void onStart(final Intent intent, int startId) {
        super.onStart(intent, startId);

        sharedPrefUtil = new SharedPrefUtil(getApplication(),
                ShareFile.USERFILE);
        UserId = sharedPrefUtil.getString(getApplicationContext(),
                ShareFile.USERFILE, ShareFile.USERID, "");
        downtime = sharedPrefUtil.getString(
                getApplication(), ShareFile.USERFILE,
                ShareFile.UPDATENOTESETTIME, "2016-01-01%2B00:00:00");
        if (sharedPrefUtil.getString(getApplication(),
                ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (intent.getIntExtra("loadType", 0) == 0) {
                        downNewFriend();
                    } else {
                        sysNewFriend();
                    }
                }
            }).start();
        }
    }

    public void downNewFriend(){
        if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.本地通讯录下载,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String result) {
                                    if (!TextUtils.isEmpty(result)) {
                                        try {
                                            Gson gson = new Gson();
                                            NewFriendsActivity.newFriendBean bean = gson.fromJson(result, NewFriendsActivity.newFriendBean.class);
                                            if (bean.status == 0) {

                                                List<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> list = bean.page.items;

                                                if (list != null) {
                                                    for (NewFriendsActivity.newFriendBean.PageBean.ItemsBean listBean : list){
                                                        App.getDBcApplication().saveNewFriendData(listBean,0);
                                                    }
                                                }
                                            }
                                        } catch (JsonSyntaxException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.d("TAG", "error:" + volleyError.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("uId", UserId);// "52432"
                            return map;
                        }
                    };
                    stringRequest.setTag("downf");
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                    App.queues.add(stringRequest);
                }
            }).start();
        }
    }

    /**
     * 本地联系人同步
     */
    public void sysNewFriend(){
        final List<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> listBeanList = App.getDBcApplication().getAllNewFriendData(UserId,true);
        if (listBeanList.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            try {
                JSONArray jsonArray = new JSONArray();
                for (NewFriendsActivity.newFriendBean.PageBean.ItemsBean bean : listBeanList) {
                    JSONObject object = new JSONObject();
                    object.put("id", bean.id);
                    object.put("puid", bean.puid);
                    object.put("remark", bean.remark);
                    object.put("remark1", bean.remark1);
                    object.put("changeTime", bean.changeTime);
                    object.put("createTime", bean.createTime);
                    object.put("pname", bean.pname);
                    object.put("pimgs", bean.pimgs);
                    object.put("type", bean.type);
                    object.put("updateState", App.getDBcApplication().getNewFriendUpdateState(bean.puid));
                    object.put("uid", bean.uid);
                    jsonArray.put(object);
                }
                jsonObject.put("says", jsonArray);
                HttpUtils httpUtils = new HttpUtils(10000);
                RequestParams params = new RequestParams();
                params.addBodyParameter("data", jsonObject.toString());
                httpUtils.send(HttpMethod.POST, URLConstants.本地通讯录同步, params,
                        new RequestCallBack<String>() {

                            @Override
                            public void onFailure(HttpException e, String msg) {
                                Log.e("TAG", "本地通讯录同步失败" + msg);
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                if (!TextUtils.isEmpty(responseInfo.result)) {
                                    Gson gson = new Gson();
                                    NoteService.noteSynBean bean = gson.fromJson(responseInfo.result, NoteService.noteSynBean.class);
                                    if (bean.status == 0) {
                                        List<NoteService.noteSynBean.ListBean> listBeans = bean.list;
                                        if (listBeans != null) {
                                            for (NoteService.noteSynBean.ListBean listBean : listBeans) {

                                                if (listBean.dataState == 1) {//新增
                                                    if (listBean.state == 0) {//成功
                                                        //修改id和状态值
                                                        App.getDBcApplication().updateNewFriendId(listBean.id, listBean.calendId, UserId);
                                                        App.getDBcApplication().updateNewFriendState(listBean.calendId, UserId, 0);
                                                    } else if (listBean.state == 1) {//失败  可以不操作,但是避免意外
                                                        //更改状态为1
                                                        App.getDBcApplication().updateNewFriendState( listBean.id, UserId, 1);
                                                    } else if (listBean.state == 2) { //异常
                                                        App.getDBcApplication().updateNewFriendState( listBean.id, UserId, -1);
                                                    }
                                                } else if (listBean.dataState == 2) {//修改
                                                    if (listBean.state == 0) {//成功
                                                        //修改该id状态值
                                                        App.getDBcApplication().updateNewFriendState( listBean.id, UserId, 0);
                                                    } else if (listBean.state == 1) {//失败
                                                        //更改状态为2
                                                        App.getDBcApplication().updateNewFriendState( listBean.id, UserId, 2);
                                                    } else if (listBean.state == 2) { //异常
                                                        App.getDBcApplication().updateNewFriendState( listBean.id, UserId, -1);
                                                    }
                                                } else if (listBean.dataState == 3) {//删除
                                                    if (listBean.state == 0) {//成功
                                                        //删除该id的清单
                                                        App.getDBcApplication().deleteNewFriendData(listBean.id, UserId, false);
                                                    } else if (listBean.state == 1) {//失败
                                                        //更改状态为3
                                                        App.getDBcApplication().updateNewFriendState( listBean.id, UserId, 3);
                                                    } else if (listBean.state == 2) { //异常
                                                        App.getDBcApplication().updateNewFriendState( listBean.id, UserId, -1);
                                                    }
                                                }
                                            }
                                        }
                                        sharedPrefUtil.putString(
                                                getApplication(),
                                                ShareFile.USERFILE,
                                                ShareFile.UPDATENOTESETTIME,
                                                bean.downTime.replace("T", " "));
                                    }
                                }
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
